#include "search.hpp"
#include "./httplib/httplib.h"

const string input_file("./data/clean_html/data.txt");
const string root_path("./wwwroot");


 void usage(const char* prompt)        
 {                                
    std::cout << "Usage: " << prompt << " port" << std::endl;
 } 

int main(int argc,char* argv[])
{
    if (2 != argc)
    {
        usage(argv[0]);
 
        exit(1);                                                                                                                                         
    }

    ns_search::search s;
    s.InitSearch(input_file);

    httplib::Server server;
    server.set_base_dir(root_path.c_str());

    server.Get("/s",[&s](const httplib::Request &req, httplib::Response &rsp)
        {
            if(!req.has_param("word"))
            {
                rsp.set_content("please input keyword","text/plain; charset=utf-8");
                
                return;
            }

            string query = req.get_param_value("word");
            string log_message("Client search：");
            log_message += query;
            LOG(NORMAL,log_message);

            //std::cout << "Client search：" << query << std::endl;
            string json_str;
            s.Search(query,&json_str);
            rsp.set_content(json_str,"application/json");
        });
    
    int port = stoi(string(argv[1]));

    server.listen("0.0.0.0",port);
    LOG(NORMAL,"Service startup succeeded");   
    
    return 0;
}